package com.nsash.chat;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.nsash.chat.async.ChatTask;
import com.nsash.dto.ChatMessages;
import com.nsash.dto.Message;
import com.nsash.dto.Rooms;

/**
 * A fragment representing a list of Items.
 * <p />
 * Large screen devices (such as tablets) are supported by replacing the
 * ListView with a GridView.
 * <p />
 * Activities containing this fragment MUST implement the {@link Callbacks}
 * interface.
 */
public class ChatRoomFragment extends Fragment implements
		AbsListView.OnItemClickListener, View.OnClickListener {

	// TODO: Rename parameter arguments, choose names that match
	// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
	public static final String ACTIVATE_ROOM = "activatedRoom";

	// TODO: Rename and change types of parameters
	private String roomActive;

	private OnFragmentInteractionListener mListener;
	private OnFragmentSendListener mSendListener;

	/**
	 * The fragment's ListView/GridView.
	 */
	private AbsListView mListView;

	/**
	 * The Adapter which will be used to populate the ListView/GridView with
	 * Views.
	 */
	private ListAdapter mAdapter;

	private ChatTask chat;
	private ChatMessages messages = new ChatMessages();

	private EditText mOutEditText;

	private Button mSendButton;
	
	// TODO: Rename and change types of parameters
	public static ChatRoomFragment newInstance(String roomToActive) {
		ChatRoomFragment fragment = new ChatRoomFragment();
		Bundle args = new Bundle();
		args.putString(ACTIVATE_ROOM, roomToActive);
		fragment.setArguments(args);
		return fragment;
	}

	/**
	 * Mandatory empty constructor for the fragment manager to instantiate the
	 * fragment (e.g. upon screen orientation changes).
	 */
	public ChatRoomFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments() != null) {
			roomActive = getArguments().getString(ACTIVATE_ROOM);
		}

		mAdapter = new ArrayAdapter<Message>(getActivity(),
				android.R.layout.simple_list_item_1, android.R.id.text1,
				messages.ITEMS);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_chatroom, container,
				false);

		// Set the adapter
		mListView = (AbsListView) view.findViewById(android.R.id.list);
		((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

		// Set OnItemClickListener so we can be notified on item clicks
		mListView.setOnItemClickListener(this);

        // Initialize the compose field with a listener for the return key
        mOutEditText = (EditText) this.getActivity().findViewById(R.id.edit_text_out);
        
        // Initialize the send button with a listener that for click events
        mSendButton = (Button) this.getActivity().findViewById(R.id.button_send);
        mSendButton.setOnClickListener(this);

		chat = new ChatTask(mAdapter, messages, roomActive);
		chat.execute("");
		
		return view;
	}
	
	private void sendMessage(String message) {
		 try {
			chat.sendMessage(message);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnFragmentInteractionListener) activity;
			mSendListener = (OnFragmentSendListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentInteractionListener");
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
		mSendListener = null;
	}

	public void onSendClick(AdapterView<?> parent, View view, String message) {
		if (null != mSendListener) {
			// Notify the active callbacks interface (the activity, if the
			// fragment is attached to one) that an item has been selected.
			mSendListener.onFragmentSend(message);
		}
	}
	
	public void onClick(View v) {
        String message = mOutEditText.getText().toString();
		sendMessage(message);
		mOutEditText.setText("");
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (null != mListener) {
			// Notify the active callbacks interface (the activity, if the
			// fragment is attached to one) that an item has been selected.
			mListener
					.onFragmentInteraction(messages.ITEMS.get(position).id);
		}
	}

	/**
	 * The default content for this Fragment has a TextView that is shown when
	 * the list is empty. If you would like to change the text, call this method
	 * to supply the text it should use.
	 */
	public void setEmptyText(CharSequence emptyText) {
		View emptyView = mListView.getEmptyView();

		if (emptyText instanceof TextView) {
			((TextView) emptyView).setText(emptyText);
		}
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(String id);
	}

	public interface OnFragmentSendListener {
		// TODO: Update argument type and name
		public void onFragmentSend(String id);
	}
	
	@Override
	public void onDestroy() {
		if(!chat.isCancelled())
			chat.cancel(true);
		super.onDestroy();
	}
	
	@Override
	public void onDestroyView() {
		if(!chat.isCancelled())
			chat.cancel(true);
		super.onDestroyView();
	}

}
